/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.goods.web;

import com.jeesite.common.cache.JedisUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.config.MyProps;
import com.jeesite.modules.goods.entity.*;
import com.jeesite.modules.goods.service.BrandService;
import com.jeesite.modules.goods.service.GoodsTypeService;
import com.jeesite.modules.goods.service.ZtGoodsService;
import com.jeesite.modules.jdProduct.utils.ProductPoolUtils;
import com.jeesite.modules.pay.wxpay.api.UUID;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.task.TaskUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试数据Controller
 * 
 * @author ThinkGem
 * @version 2018-04-22
 */
@Controller
@RequestMapping(value = "${adminPath}/ztBeiGoods")
public class ZtBeiGoodsController extends BaseController {

	@Autowired
	private ZtGoodsService ztGoodsService;
	
	@Autowired
	private BrandService brandService;
	
	@Autowired	
	private UserService userService;
	
	@Autowired  
    private MyProps myProps;

	@Autowired
	private GoodsTypeService goodsTypeService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public ZtGoods get(String id, boolean isNewRecord) {
		return ztGoodsService.get(id, isNewRecord);
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:view")
	@RequestMapping(value = { "list", "" })
	public String list(ZtGoods ztGoods, Model model) {
		model.addAttribute("ztGoods", ztGoods);
		List<Brand> brandList=brandService.findList(new Brand());
		model.addAttribute("brandList", brandList);//品牌
		GoodsType gt=new GoodsType();
		gt.setState(1);
		List<GoodsType> typeList=goodsTypeService.findList(gt);
		model.addAttribute("typeList", typeList);//类别
		
		return "modules/ztGoods/ztBeiGoodsList";
	}
	

	/*@RequestMapping(value ="brandList")
	public String brandList(String brandid, Model model,HttpSession session) {
		session.setAttribute("ztGoodsbrandid", brandid);
		Brand brand=new Brand();
		brand.setId(brandid);
		brand=brandService.get(brand);
		model.addAttribute("brandName", brand.getName());
		return "modules/ztGoods/ztGoodsBrandList";
	}
	
	@RequestMapping(value = "brandListData")
	@ResponseBody
	public Page<ZtGoods> brandListData(ZtGoods ztGoods, HttpServletRequest request,HttpSession session,
			HttpServletResponse response,Model model) {
		String brandid=session.getAttribute("ztGoodsbrandid").toString();
		ztGoods.setGoodstemp("3");
		ztGoods.setBrandid(brandid);
		Page<ZtGoods> page = ztGoodsService.findPage(new Page<ZtGoods>(request,
				response), ztGoods);
		
		
		return page;
	}*/
	

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<ZtGoods> listData(ZtGoods ztGoods, HttpServletRequest request,
			HttpServletResponse response,Model model) {
		String type="";
		if(StringUtils.isNotBlank(ztGoods.getOneType())){
			type=ztGoods.getOneType();
		}
		if(StringUtils.isNotBlank(ztGoods.getTwoType())){
			type+=","+ztGoods.getTwoType();
		}
		if(StringUtils.isNotBlank(ztGoods.getThreeType())){
			type+=","+ztGoods.getThreeType();
		}
		ztGoods.setType(type);
		ztGoods.setSjStatus("3");
		if(StringUtils.isBlank(ztGoods.getTag())){
			ztGoods.setTag(null);
		}
		Page<ZtGoods> page = ztGoodsService.findPage(new Page<ZtGoods>(request,
				response), ztGoods);
	
		
		return page;
	}
	
	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:view")
	@RequestMapping(value = "form")
	public String form(ZtGoods ztGoods, Model model,HttpServletRequest request,HttpServletResponse response) {
		
		if(ztGoods!=null&&StringUtils.isBlank(ztGoods.getId())){
			ztGoods.setZtGoodsid(String.valueOf(UUID.next()));
		}
		if(ztGoods.getWeig()==null){
			ztGoods.setWeig("0");
		}
		if(ztGoods.getSpotid()==null){
			ztGoods.setSpotid(0);
		}
		if(StringUtils.isBlank(ztGoods.getId())&&ztGoods.getSpotid()==0){
			ztGoods.setCode(String.valueOf(System.currentTimeMillis()));
		}
		model.addAttribute("ztGoods", ztGoods);
		
		List<Brand> brandList=brandService.findList(new Brand());
		model.addAttribute("brandList", brandList);//品牌
		
		List<GoodsType> typeList=goodsTypeService.findList(new GoodsType());
		model.addAttribute("typeList", typeList);//类别
		
		User user=new User();
		user.setMgrType(User.MGR_TYPE_CORP_ADMIN);	// 租户管理员
		
		// 禁用自动添加租户代码条件，添加自定义租户查询条件
		user.getSqlMap().getWhere().disableAutoAddCorpCodeWhere()
			.and("corp_code", QueryType.EQ, user.getCorpCode_())
			.and("corp_name", QueryType.LIKE, user.getCorpName_());
		
		List<User> userList = userService.findList(user);
		ZtMle ztMle = null;
		ZtSk ztSk = null;
		if(ztGoods!=null){
			if(StringUtils.isNotBlank(ztGoods.getType())){
				String[] goodsTypeArr=ztGoods.getType().split(",");
				for(int ii=goodsTypeArr.length-1;ii>=0;ii--){
					String goodsCode=goodsTypeArr[ii];
					Object obj=JedisUtils.getObject("ztSkContro"+goodsCode);
					if(obj!=null){
						ztSk=(ZtSk)obj;
						break;
					}
				}
				for(int ii=goodsTypeArr.length-1;ii>=0;ii--){
					String goodsCode=goodsTypeArr[ii];
					Object obj=JedisUtils.getObject("ztMleContro"+goodsCode);
					if(obj!=null){
						ztMle=(ZtMle)obj;
						break;
					}
				}
			}
		}
		if(ztSk==null) {
			ztSk = (ZtSk) JedisUtils.getObject("ztSkContro");
		}
		if(ztMle==null) {
			ztMle = (ZtMle) JedisUtils.getObject("ztMleContro");
		}
		model.addAttribute("ztSk", ztSk);
		model.addAttribute("ztMle", ztMle);


		return "modules/ztGoods/ztBeiGoodsForm";
	}
	
	

	/**
	 * 保存数据  /wewoo/userfiles/fileupload/
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated ZtGoods ztGoods) {
		
		String discount=ztGoods.getDiscount()==null?"1":ztGoods.getDiscount(); 
		ztGoods.setDiscountPrice(ztGoods.getCommonPrice()*(Double.valueOf(discount).doubleValue()));
		if(ztGoods.getNewPrice()==null||ztGoods.getNewPrice()<=0){
			ztGoods.setNewPrice(ztGoods.getDiscountPrice());
		}
		if(ztGoods.getBuyQuantity()==null){
			ztGoods.setBuyQuantity(0);
		}
		ztGoodsService.save(ztGoods);
		
		return renderResult(Global.TRUE, text("保存商品成功！"));
	}
	
	/**
	 * 下架
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(ZtGoods ztGoods) {
		ztGoods.setSjStatus("2");
		ztGoodsService.updateSjStatus(ztGoods);
		return renderResult(Global.TRUE, text("下架商品成功"));
	}
	/**
	 * 更换定价
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "tag")
	@ResponseBody
	public String tag(ZtGoods ztGoods) {
		String tag=ztGoods.getTag();
		if("2".equals(tag)&&ztGoods.getSpotid()==1){//自定义的更换
			ztGoods=ProductPoolUtils.refreshPrice(ztGoods.getCode(),ztGoods);
		}else if("2".equals(tag)&&ztGoods.getSpotid()!=1){//
			ztGoods=TaskUtils.fixPrice(ztGoods);
		}else{//
			ztGoods.setTag("2");
		}
		ztGoodsService.save(ztGoods);
		return renderResult(Global.TRUE, text("更换定价模式成功"));
	}
	@RequestMapping(value = "ishidden")
	@ResponseBody
	public String ishidden(ZtGoods ztGoods) {
		
		String goodstemp=ztGoods.getGoodstemp().replace(",3", "");
		ztGoods.setGoodstemp(goodstemp);
		ztGoodsService.save(ztGoods);
		return renderResult(Global.TRUE, text("商品不显示在专场成功"));
	}
	
	/**
	 * 上架
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(ZtGoods ztGoods) {
		ztGoods=ztGoodsService.get(ztGoods);
		String [] code = ztGoods.getType().split(",");
		if(code.length>=0){
			int state = goodsTypeService.getState(code);
			if (state==0){
				ztGoods.setSjStatus("1");
				ztGoods.setState(0);
				ztGoodsService.updateSjStatus(ztGoods);
				return renderResult(Global.TRUE, text("上架商品成功"));
			}else {
				return renderResult(Global.FALSE, text("类目已经下架无法上架"));
			}
		}else {
			ztGoods.setSjStatus("1");
			ztGoods.setState(0);
			ztGoodsService.updateSjStatus(ztGoods);
			return renderResult(Global.TRUE, text("上架商品成功"));
		}
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(ZtGoods ztGoods) {
		ztGoodsService.delete(ztGoods);
		return renderResult(Global.TRUE, text("删除商品成功！"));
	}
	
	/**
	 * 批量下架
	 * @param ztGoods
	 * @return
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "batchDisable")
	@ResponseBody
	public String batchDisable(String goodsString) {
		
		if(StringUtils.isNotBlank(goodsString)){
			String[] strArr=goodsString.split(",");
			List<ZtGoods> list=new ArrayList<ZtGoods>();
			for(String str:strArr){
				ZtGoods ztGoods=new ZtGoods();
				ztGoods.setId(str);
				ztGoods.setSjStatus("2");
				list.add(ztGoods);
			}
			ztGoodsService.batchUpdateSjStatus(list);
		}
		
		return renderResult(Global.TRUE, text("下架商品成功"));
	}
	
	/**
	 * 批量上架
	 * @param ztGoods
	 * @return
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "batchEnable")
	@ResponseBody
	public String batchEnable(String goodsString) {
		boolean boo = false;
		if(StringUtils.isNotBlank(goodsString)){
			String[] strArr=goodsString.split(",");
			List<ZtGoods> list=new ArrayList<ZtGoods>();

			for(String str:strArr){
				ZtGoods ztGoods=new ZtGoods();
				ztGoods.setId(str);
				ztGoods=ztGoodsService.get(ztGoods);
				String [] code = ztGoods.getType().split(",");
				if(code.length>=0){
					int state = goodsTypeService.getState(code);
					if (state==0){
						ztGoods.setSjStatus("1");
						ztGoods.setState(0);
						ztGoodsService.updateSjStatus(ztGoods);
						list.add(ztGoods);
					}else {
						boo=true;
					}
				}else {
					ztGoods.setSjStatus("1");
					ztGoods.setState(0);
					ztGoodsService.updateSjStatus(ztGoods);
					list.add(ztGoods);
				}
			}
			if(list.size()>0){
				ztGoodsService.batchUpdateSjStatus(list);
			}

		}
		if(boo){
			return renderResult(Global.TRUE, text("部分商品上架成功，部分商品因为类目下架无法上架"));
		}else {
			return renderResult(Global.TRUE, text("上架商品成功"));
		}
	}

	String sj="0";
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "priceUpdate")
	@ResponseBody
	public String priceUpdate(String goodsString) {
		ExecutorService cachedThreadPool=ProductPoolUtils.cachedThreadPool;
		if(cachedThreadPool==null){
			cachedThreadPool=Executors.newCachedThreadPool();
		}
		sj = goodsString;
		cachedThreadPool.execute(new Runnable() {			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				List<ZtGoods> plpList=new ArrayList<ZtGoods>();
				ZtGoods ztGoods = new ZtGoods();
				if (!sj.equals("0")){
					ztGoods.setSjStatus(sj);
				}
				ztGoods.setSpotid(1);
				List<ZtGoods> plp=ztGoodsService.findList(ztGoods);
				String skus="";
					for(int i=0;i<plp.size();i++){
						if(plp.get(i).getSpotid()==1){
							skus=plp.get(i).getCode();
							plpList.add(ProductPoolUtils.refreshPrice(skus,plp.get(i)));//京东的商品
						}
						if((i%100)==0 && i != 0){
							ztGoodsService.batchUpdatePrice(plpList);
							plpList.clear();
							plpList=new ArrayList<ZtGoods>();
						}
				}
					if(plpList!=null && plpList.size()>0){
					ztGoodsService.batchUpdatePrice(plpList);
				}
			}
		});
		
		return renderResult(Global.TRUE, text("定价在进行中，需要点时间!"));
	}
	/**
	 * 批量添加归类
	 * @param ztGoods
	 * @return
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "btnAddType")
	@ResponseBody
	public String btnAddType(String goodsString,String temp) {
		
		if(StringUtils.isNotBlank(goodsString)){
			String[] strArr=goodsString.split(",");
			List<ZtGoods> list=new ArrayList<ZtGoods>();
			for(String str:strArr){
				ZtGoods ztGoods=new ZtGoods();
				ztGoods.setId(str);
				ztGoods=ztGoodsService.getGoodstemp(ztGoods);
				String goodstemp=ztGoods.getGoodstemp();
				
				if(StringUtils.isNotBlank(goodstemp)){
					if(!goodstemp.contains(temp)){
						goodstemp+=","+temp;
						ztGoods.setGoodstemp(goodstemp);
						list.add(ztGoods);
					}
				}else{
					goodstemp=temp;
					ztGoods.setGoodstemp(goodstemp);
					list.add(ztGoods);
				}
				
				
			}
			if(list!=null && list.size()>0){
				ztGoodsService.batchUpdateGoodstemp(list);
			}
		}
		
		return renderResult(Global.TRUE, text("商品添加归类成功"));
	}
	
	/**
	 * 批量添加归类
	 * @param ztGoods
	 * @return
	 */
	@RequiresPermissions("ztBeiGoods:ztBeiGoodsData:edit")
	@RequestMapping(value = "btnDelType")
	@ResponseBody
	public String btnDelType(String goodsString,String temp) {
		
		if(StringUtils.isNotBlank(goodsString)){
			String[] strArr=goodsString.split(",");
			List<ZtGoods> list=new ArrayList<ZtGoods>();
			for(String str:strArr){
				ZtGoods ztGoods=new ZtGoods();
				ztGoods.setId(str);
				ztGoods=ztGoodsService.getGoodstemp(ztGoods);
				String goodstemp=ztGoods.getGoodstemp();
				if(StringUtils.isNotBlank(goodstemp)){
					if(goodstemp.contains(temp)){
						
						
						if(goodstemp.contains((temp+","))){//
							goodstemp=goodstemp.replace(temp+",", "");
							ztGoods.setGoodstemp(goodstemp);
							list.add(ztGoods);
						}else{
							if(goodstemp.contains((","+temp))){//
								goodstemp=goodstemp.replace(","+temp, "");
								ztGoods.setGoodstemp(goodstemp);
								list.add(ztGoods);
							}
						}
						
					}
				}
				
				
			}
			if(list!=null && list.size()>0){
				ztGoodsService.batchUpdateGoodstemp(list);
			}
		}
		
		return renderResult(Global.TRUE, text("商品删除归类成功"));
	}
	}